﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Threading;
using System.IO.IsolatedStorage;
using System.IO;
using System.Windows.Threading;
using System.Collections.Generic;

namespace WindowsPhoneAudioStreaming.Audio.Streaming {
    public static class TraceLogger {
        public static readonly Mutex TracerMutex = new Mutex(false, "TraceLogger");
        public const string LogFileName = "Streaming.Tracer.txt";
        static IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
        static int logItemNumber = 0;
        static DispatcherTimer timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(5) };
        static List<string> traceList = new List<string>();

        static public void TraceInitialise() {
            store = IsolatedStorageFile.GetUserStoreForApplication();
            if (store.FileExists(LogFileName)) {
                store.DeleteFile(LogFileName);
            }
            timer.Tick += LogWriteTimerTick;
            timer.Start();
        }

        private static void LogWriteTimerTick(object sender, EventArgs e) {
            if (traceList.Count > 0) { ThreadPool.QueueUserWorkItem(Write);}                
        }

        static public void WriteTrace(string trace) {
            lock (traceList) {
                logItemNumber++;
                traceList.Add("(" + logItemNumber.ToString() + ") " + DateTime.Now.ToLongTimeString() + ":" + (string)trace);
            }
        }

        static private void Write(object trace) {
            try {
                TracerMutex.WaitOne();
                using (var istream = new IsolatedStorageFileStream(LogFileName, FileMode.Append, FileAccess.Write, FileShare.Read, store))
                using (var sw = new StreamWriter(istream)) {
                    lock (traceList) {
                        foreach (var item in traceList) {
                            sw.WriteLine(item);                            
                        }
                        traceList.Clear();
                    }
                }
            }
            finally {
                TracerMutex.ReleaseMutex();
            }
        }
    }
}
